package com.project.base.action;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.project.base.entity.BaseEntity;
import com.project.base.service.BaseService;

public class BaseAction <T extends BaseEntity, S extends BaseService<T, String>> extends ActionSupport implements Preparable{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6944075013129472173L;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public BaseAction(){
	    Type type = getClass().getGenericSuperclass();
	    if ((type != null) && ((type instanceof ParameterizedType))) {
	      Type t = ((ParameterizedType)type).getActualTypeArguments()[0];
	      if ((t instanceof Class))
	        this.entityClass = ((Class)t);
	    }
	}
	

	@Override
	public void prepare() throws Exception {
	    try {
			if(id!=null&&!"".equals(id)){
				entity = entityClass.newInstance();
			}else{
				entity = entityClass.newInstance();
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 添加方法
	 * @return "add-success"
	 */
	public String add(){
		service.saveObject(entity);
		return "add-success";
	}
	
	protected T entity;
	protected Class<T> entityClass;
	protected S service;
	protected String id;
	
	public T getEntity() {
		return entity;
	}
	
	public void setEntity(T entity) {
		this.entity = entity;
	}
	
	public S getService() {
		return service;
	}
	
	public void setService(S service) {
		this.service = service;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
}
